<?php

class HomeController extends Controller {

    /**
     * 
     */
    public function actionIndex() {
        $this->render('index', array());
    }

    /**
     * 
     */
    public function actionStar($product_id = null, $star_value = 5) {
        $error = true;
        $this->layout = false;
        $message = $view = "";
        if ($product_id != null) {
            if (!Yii::app()->user->isGuest) {
                $product = Product::model()->findByPk($product_id);
                $product->count_rating = $product->count_rating + 1;
                $product->total_rating = $product->total_rating + $star_value;
                $product->avg_rating = round($product->total_rating / $product->count_rating, 1);
                if ($product->save()) {
                    $id = Yii::app()->user->id;
                    $star = new Star();
                    $star->star = $star_value;
                    $star->object_id = $product_id;
                    $star->user_id = $id;
                    $star->created = date('y-m-d H:i:s');
                    $star->save();
                    $message = "Bạn đã đánh giá sản phẩm thành công";
                    $error = false;
                    $view = $this->render('star', array('product' => $product), true);
                }
            } else {
                $message = "Bạn phải đăng nhập trước khi đánh giá sản phẩm";
            }
        }
        echo json_encode(array('error' => $error, 'message' => $message, 'view' => $view));
        die();
    }

    /**
     * 
     */
    public function actionRegister() {
        $error = false;
        $message = "";
        if (isset($_REQUEST['email']) && isset($_REQUEST['gender'])) {
            if (strlen($_REQUEST['email']) > 0) {
                $email = new Email();
                $email->gender = $_REQUEST['gender'];
                $email->email = $_REQUEST['email'];
                $email->created = date('Y-m-d h:i:s');
                if ($email->save()) {
                    
                } else {
                    foreach($email->getErrors("email") as $value){
                        $message .= "\n".$value;
                    }
                    $error = true;
                }
            }else{
                $error = true;
                $message = "email không được bỏ trống";
            }
        }
        echo json_encode(array('error' => $error, 'message' => $message));
        die();
    }

}